package com.ouc.controller;

import com.ouc.common.Result;
import com.ouc.entity.ShippingAddress;
import com.ouc.entity.User;
import com.ouc.service.ShippingAddressService;
import com.ouc.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;


@RestController
@RequestMapping("/user")
@CrossOrigin
@Api(tags = "登陆用户相关接口", description = "提供用户登陆接口的返回信息")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private ShippingAddressService shippingAddressService;

    @ApiOperation("用户登陆接口")
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        List<User> allUsers = userService.getAllUser();
        for (int i = 0; i < allUsers.size(); i++) {
            if (Objects.equals(allUsers.get(i).getUsername(), user.getUsername())) {
                if (Objects.equals(allUsers.get(i).getPassword(), user.getPassword())) {
                    return Result.ok()
                            .data("userId", allUsers.get(i).getId())
                            .data("userRole", allUsers.get(i).getRole())
                            .data("userName", allUsers.get(i).getUsername());
                }
            }
        }
        return Result.error().data("description", "账号密码不正确，请重新输入！");
    }

    @ApiOperation("增加新地址接口")
    @PostMapping("/createaddress")
    public Result createNewAddress(@RequestBody ShippingAddress shippingAddress) {
        //代码结构如下
        //在表中查询当前用户是否有该地址，如果没有的话需要进行插入
        if (!shippingAddressService.existAddress(shippingAddress)) {
            if (shippingAddressService.insertAddress(shippingAddress)) {
                return Result.ok().data("msg", "已将地址插入到当前数据库中");
            } else {
                return Result.error().data("msg", "插入地址失败");
            }
        } else {
            //如果有该地址就返回给用户已经存在的信息提示
            return Result.ok().data("warn", "当前地址信息在数据库中已经存在");
        }
    }

    @ApiOperation("得到用户所有的地址")
    @GetMapping("/getalladdress")
    public Result getAllAddress(Integer userId) {
        return Result.ok()
                .data("addresses", shippingAddressService.getAllAddress(userId));
    }

    @ApiOperation("删除地址")
    @PostMapping("/deleteaddress/{id}")
    public Result deleteAddress(@PathVariable("id") Integer id) {
        return shippingAddressService.deleteAddress(id) ?
                Result.ok()
                        .data("msg", "删除地址成功") :
                Result.error()
                        .data("warn", "删除地址失败！");
    }


}
